﻿using ControlHelper;
using Creator.Core;
using Creator.Core.Base;
using DesktopCreator.ViewModel;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Xml.Linq;

namespace DesktopCreator.Controls
{
    /// <summary>
    /// Hirerachy.xaml 的交互逻辑
    /// </summary>
    public partial class Hirerachy : UserControl
    {
        public Hirerachy()
        {
            InitializeComponent();

            tvObjects.SelectedItemChanged += TreeViewItem_Selected;
            tvComponent.SelectedItemChanged += TreeViewItem_Selected;
            tvObjects.MouseDoubleClick += TvObjects_MouseDoubleClick;

        
        }
 

        public static Action<double, double> OnDoubleClick;
        private void TvObjects_MouseDoubleClick(object sender, MouseButtonEventArgs e)
        { 
            if (tvObjects.SelectedItem is TreeViewItem item && item.DataContext is BaseObjectViewModel obj)
            { 
                OnDoubleClick?.Invoke(obj.Object.PosX, obj.Object.PosY); 
            } 
        }
        private void TreeViewItem_Selected(object sender, RoutedEventArgs e)
        {
            var treeView = sender as TreeView;
            if (treeView.SelectedItem is TreeViewItem item && item.DataContext is BaseObjectViewModel obj)
            {
                SelectItem(obj); 
            }
        
        }
        /// <summary>
        /// 初始化层级的数据
        /// 设置之前会清空所有数据
        /// </summary>
        /// <param name="list"></param>
        public void SetData(IList list)
        {
            if (list == null) return;//在系统处于初始的状态，这里可能为null
            var genericType = list.GetType().GetGenericArguments()[0];
            if(genericType == typeof(ProcessObject))
            {
                tvComponent.Items.Clear();
                foreach (var pb in  list as List<ProcessObject>)
                {
                    tvComponent.Items.Add(GetTreeViewItem(pb));
                } 
            }
            //这个类型的数据不会保存在本地，这里基本基本没用
            else if(genericType == typeof(BaseObject))
            {
                tvObjects.Items.Clear();
                foreach (var pb in list as List<BaseObject>)
                {
                    tvObjects.Items.Add(GetTreeViewItem(pb));
                }
            }
          
        }
          
        private void SelectItem(BaseObjectViewModel obj)
        {
            if (obj == null) return;
            Editor.OnSelectedObject?.Invoke(obj); 
        }

        private void MenuItem_ClickCreateNewObject(object sender, RoutedEventArgs e)
        {
            var po = new ProcessObject(true);
            tvComponent.Items.Add(GetTreeViewItem(po)); 
            SystemData.ProcessObjects.Add(po);
        }

        /// <summary>
        /// 创建树形项
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        TreeViewItem GetTreeViewItem(BaseObject obj)
        {
            TreeViewItem treeViewItem = new TreeViewItem();
            BaseObjectViewModel bovm = new BaseObjectViewModel(obj); 
            treeViewItem.DataContext = bovm;  
            treeViewItem.Header = ControlHepler.CreateBindTextBox("Name");
            treeViewItem.SetBinding(TreeViewItem.ForegroundProperty, ControlHepler.CreateBinding("ActiveColor")); 

            // 创建右键菜单
            ContextMenu contextMenu = new ContextMenu(); 
            // 添加 "删除" 菜单项
            MenuItem deleteItem = new MenuItem();
            deleteItem.Header = "删除";
            deleteItem.Click += (ts, te) =>
            {
                tvComponent.Items.Remove(treeViewItem);
                Inspector.Clear?.Invoke();
                if(obj is ProcessObject po)
                  SystemData.ProcessObjects.Remove(po);
            };
            contextMenu.Items.Add(deleteItem);

            // 将右键菜单分配给 TreeViewItem
            treeViewItem.ContextMenu = contextMenu;
             
            return treeViewItem;
        }
        #region 拖动
        private TreeViewItem draggedItem;
        private Point startPoint;
        private void TreeViewItem_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            draggedItem = sender as TreeViewItem;
            startPoint = e.GetPosition(null);
        }

        private void TreeViewItem_MouseMove(object sender, MouseEventArgs e)
        {
            if (e.LeftButton == MouseButtonState.Pressed && draggedItem != null)
            {
                Point mousePos = e.GetPosition(null);
                Vector diff = startPoint - mousePos;

                if (Math.Abs(diff.X) > SystemParameters.MinimumHorizontalDragDistance ||
                    Math.Abs(diff.Y) > SystemParameters.MinimumVerticalDragDistance)
                {
                    DragDrop.DoDragDrop(draggedItem, draggedItem, DragDropEffects.Move);
                    draggedItem = null;
                }
            }
        }

        private void TreeViewItem_PreviewMouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            draggedItem = null;
        }

        private void TreeView_DragEnter(object sender, DragEventArgs e)
        {
            if (!e.Data.GetDataPresent(typeof(TreeViewItem)) || sender == e.Source)
            {
                e.Effects = DragDropEffects.None;
            }
        }

        private void TreeView_Drop(object sender, DragEventArgs e)
        {
            if (e.Data.GetDataPresent(typeof(TreeViewItem)))
            {
                string header =  ((TreeViewItem)e.Data.GetData(typeof(TreeViewItem))).Header.ToString();

                TreeViewItem newItem = new TreeViewItem();
                newItem.Header = header;

                if (e.Source is TreeView)
                {
                    // If dropped on the TreeView, add as root item
                    tvObjects.Items.Add(newItem);
                }
                else if (e.Source is TreeViewItem)
                {
                    // If dropped on a TreeViewItem, add as child item
                    TreeViewItem targetItem = (TreeViewItem)e.Source;
                    targetItem.Items.Add(newItem);
                    targetItem.IsExpanded = true;
                }
            }
        }
        #endregion
    }
}
